package henu.action;

import henu.bean.Car;
import henu.bean.Insurance;
import henu.bean.InsuranceCarPInformation;
import henu.bean.ManagePerson;
import henu.bean.PInformation;
import henu.dao.factory.DaoFactory;
import henu.util.AJAX;
import henu.util.CONSTANTS;
import henu.util.Page;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class InsuranceAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String args;
	private AJAX ajax = new AJAX();
	private String url;
	private Insurance insurance;
	//private List<Insurance> list;

	List<InsuranceCarPInformation> list=null;
	public List<InsuranceCarPInformation> getList() {
		return list;
	}
	public void setList(List<InsuranceCarPInformation> list) {
		this.list = list;
	}
	// 文件下载
	private String res;
	private String resName;
	private String resType;

	// 分页排序
	private Page page = new Page();
	private int pageNum = 1;
	private int numPerPage = 10;
	private String orderField = "qid";
	private String orderDirection = "asc";
	// 检索
	private String property = "-1";
	private String key = "-1";
	private Insurance i=null;
	//用于用户添加保险时获取carid
	private Car car;
	
	//用于在add或edit显示通过idcard从car表中查到的车牌号
	private String vehicle;
	//前台用户保险列表
	private List<Insurance> list1;
	//前台交强险文件上传
	private File trafficfile;
	//前台商业险文件上传
	private File insurancefile;
	//文件名
	private String trafficfileFileName;
	private String insurancefileFileName;
	
	public String getInsurancefileFileName() {
		return insurancefileFileName;
	}
	public void setInsurancefileFileName(String insurancefileFileName) {
		this.insurancefileFileName = insurancefileFileName;
	}
	public String getTrafficfileFileName() {
		return trafficfileFileName;
	}
	public void setTrafficfileFileName(String trafficfileFileName) {
		this.trafficfileFileName = trafficfileFileName;
	}
	public File getTrafficfile() {
		return trafficfile;
	}
	public void setTrafficfile(File trafficfile) {
		this.trafficfile = trafficfile;
	}
	public File getInsurancefile() {
		return insurancefile;
	}
	public void setInsurancefile(File insurancefile) {
		this.insurancefile = insurancefile;
	}
	public List<Insurance> getList1() {
		return list1;
	}
	public void setList1(List<Insurance> list1) {
		this.list1 = list1;
	}
	public String getVehicle() {
		return vehicle;
	}
	public void setVehicle(String vehicle) {
		this.vehicle = vehicle;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	public Insurance getI() {
		return i;
	}
	public void setI(Insurance i) {
		this.i = i;
	}
	
	public String getArgs() {
		return args;
	}
	public void setArgs(String args) {
		this.args = args;
	}
	public AJAX getAjax() {
		return ajax;
	}
	
	public String getUrl() {
		return url;
	}
	
	public Insurance getInsurance() {
		return insurance;
	}
	public void setInsurance(Insurance insurance) {
		this.insurance = insurance;
	}
	public String getRes() {
		return res;
	}
	public void setRes(String res) {
		this.res = res;
	}
	public String getResName() {
		return resName;
	}
	public void setResName(String resName) {
		this.resName = resName;
	}
	public String getResType() {
		return resType;
	}
	public void setResType(String resType) {
		this.resType = resType;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getNumPerPage() {
		return numPerPage;
	}
	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}
	public String getOrderField() {
		return orderField;
	}
	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}
	public String getOrderDirection() {
		return orderDirection;
	}
	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}
	public String getProperty() {
		return property;
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}


	// 显示所有的记录
		public String all() {
		
			ManagePerson m=(ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
			//System.out.println(property+"!"+key+"!"+m.getComid()+"!"+page.getStart()+"!"+page.getEnd());
			if (orderField.equals("") || orderDirection.equals("")) {
				orderField = "qid";
				orderDirection = "asc";
			}
			if (property.equals("") || key.equals("")) {
				property = "-1";
				key = "-1";
			}
			//System.out.println("action查询的关键字是:" + key);
			//System.out.println("查询的依据:" + property);
			page.setProperties1("VIEW_INSURANCE_CAR_PINFO",pageNum,numPerPage,property,key,Integer.toString(m.getComid()),Integer.toString(m.getComid()));
			// 给page这个class设置属性
			
			list = DaoFactory.getInsuranceDaoInstance().findByProperty(
					property.trim(), key.trim(),Integer.toString(m.getComid()),orderDirection.trim(), page.getStart(), page.getEnd());
			url = "/admin/insuranceMessage.jsp";
		
			return SUCCESS;
		}
		public String del() {
			//System.out.println("访问到delete方法：" + args);
			// 已经得到要删除的id 调用删除方法
			int inid =Integer.parseInt(args);
			int result = DaoFactory.getInsuranceDaoInstance().deleteById(inid);
			if (result > 0) {
				HandleMsg("200", "删除成功！", "insurance","");
			} else {
				HandleMsg("300", "删除失败！", "insurance","");
				//System.out.println("删除失败");
			}
			return SUCCESS;
		}
		
			//该添加方法只有前台用户可以调用，后台调用时要重新添加其他的方法
		public String add() throws IOException {
			/**
			 * 那边提交的话可能会出现异常数据 根据type的类型重新封装bean 然后调用dao存储
			 * */
			PInformation p=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p!=null){
				
				String realPath1=ServletActionContext.getRequest().getRealPath("/upload/insurance/traffic");
				//System.out.println("realPath1:"+realPath1);
				InputStream in1 = new FileInputStream(trafficfile);
				//System.out.println("trafficfile:"+trafficfile);
				String fileType1=trafficfileFileName.substring(trafficfileFileName.lastIndexOf("."));//截取后缀
				String fileName1=insurance.getTno()+fileType1;//文件名为交强险单号+后缀
				FileOutputStream out1=new FileOutputStream(realPath1+"\\"+fileName1);
				byte[] buffer1=new byte[1024];
				int len1=0;
				while((len1=in1.read(buffer1))>0){
					out1.write(buffer1, 0, len1);
				}
					
				
				String realPath=ServletActionContext.getRequest().getRealPath("/upload/insurance/insurance");
				InputStream in = new FileInputStream(insurancefile);
				String fileType=insurancefileFileName.substring(insurancefileFileName.lastIndexOf("."));//截取后缀
				String fileName=insurance.getIno()+fileType;//文件名为商业险单号+后缀
				FileOutputStream out=new FileOutputStream(realPath+"\\"+fileName);
				byte[] buffer=new byte[1024];
				int len=0;
				while((len=in.read(buffer))>0){
					out.write(buffer, 0, len);
				}
				out1.close();
				in1.close();	
				out.close();
				in.close();
				insurance.setTrafficfile("upload/insurance/traffic/"+fileName1);
				insurance.setInsurancefile("upload/insurance/insurance/"+fileName);
				int result = DaoFactory.getInsuranceDaoInstance().add(insurance,p.getIdCard());
				if (result > 0) {
					HandleMsg("200", "添加成功!", "insurance","closeCurrent");
				} else {
					HandleMsg("300", "添加失败,请先完善车辆信息!", "insurance","closeCurrent");
				}
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
			}
			return SUCCESS;
		}
		
		public String edit(){
			
			PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			InsuranceCarPInformation icp =DaoFactory.getInsuranceDaoInstance().findByIdCard(p1.getIdCard());
			insurance=DaoFactory.getInsuranceDaoInstance().findById(icp.getInid());
			url="/front/insuranceEdit.jsp";
			return SUCCESS;
			
		}
		public String frontupdate(){
			
			PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			InsuranceCarPInformation icp =DaoFactory.getInsuranceDaoInstance().findByIdCard(p1.getIdCard());
			int result =DaoFactory.getInsuranceDaoInstance().update(icp.getInid(), insurance);
			if (result > 0) {
				HandleMsg("200", "修改成功!", "insurance","closeCurrent");
			} else {
				HandleMsg("300", "修改失败!", "insurance","closeCurrent");
			}
			return SUCCESS;
		}
		public String update() {
			/**
			 * 那边提交的话可能会出现异常数据 根据type的类型重新封装bean 然后调用dao存储
			 * */
			PInformation p=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p!=null){
				int inid =Integer.parseInt(args);
				int result = DaoFactory.getInsuranceDaoInstance().update(inid,insurance);
				
				if (result > 0) {
					HandleMsg("200", "修改成功!", "insurance","closeCurrent");
				} else {
					HandleMsg("300", "修改失败!", "insurance","closeCurrent");
				}
				
				
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
				
			}
			return SUCCESS;
		}
		//用于用户查看 通过身份证号查找视图InsuranceCarPInformation中对应的inid 再通过inid再找出对应的insurance
		public String findByInid(){
			
			PInformation p=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p!=null){
					InsuranceCarPInformation icp =DaoFactory.getInsuranceDaoInstance().findByIdCard(p.getIdCard());
					if(icp==null){
						 Car car=DaoFactory.getInsuranceDaoInstance().findvehiclebyidcard(p.getIdCard());
						//String ismaster=DaoFactory.getPInformationDaoInstance().findbyid(p.getIdCard());
						
						if(car!=null){
							vehicle=car.getVehicleLicense();
						url="/front/insuranceAdd.jsp";//*****先验证是否有完善车辆信息才能添加保险信息#####
						
						}
						else{
							//你不是车主，不能添加信息
							ajax=new AJAX();
							ajax.setMessage("您不是车主或者没有添加车辆信息，不能添加保险信息");
							ajax.setStatusCode("300");
							url = "/admin/ajax.jsp";
						}
					
				}	
				else
				{
				 i =DaoFactory.getInsuranceDaoInstance().findById(icp.getInid());
				// System.out.println("车辆id"+i.getCarid());
				url="/front/insuranceMessage.jsp";
				
				}
				return SUCCESS;
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
	 			return SUCCESS;
			}
		}
		//前台保险信息列表
		public String InsuranceMassageList(){
			PInformation p=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			list1 = new ArrayList<Insurance>();
			if(p!=null){
				//找到一个用户的所有车辆
				List<Car> listallcarid = DaoFactory.getInsuranceDaoInstance().findAllCar(p.getIdCard());
				if(listallcarid!=null){
					for(Car listcar:listallcarid){
						//System.out.println(listcar);
						//System.out.println(listcar.getCarid());
						Insurance i = DaoFactory.getInsuranceDaoInstance().findByCarid(listcar.getCarid());
						list1.add(i);
					}
					url = "/front/insuranceMessageList.jsp";
				}
					
				else
					url = "/front/insuranceMessageList.jsp";
				
				return SUCCESS;
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
	 			return SUCCESS;
			}
		}
		public String findById(){
			int inid =Integer.parseInt(args);
			insurance=DaoFactory.getInsuranceDaoInstance().findById(inid);
			url = "/front/insuranceToLook.jsp";
			return "look";
		}
		public void HandleMsg(String statusCode, String msg, String tabid,String callback) {
			ajax.setCallbackType(callback);
			ajax.setMessage(msg);
			ajax.setStatusCode(statusCode);
			ajax.setNavTabId(tabid);
			url = "/admin/ajax.jsp";
		}
}
